package com.ujson.chat.server.netty;

import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.server.handler.*;
import com.ujson.chat.server.listener.ServerChannelCloseListener;
import com.ujson.chat.server.listener.ServerConnectionListener;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <h3>ujson-parent</h3>
 * <p>netty服务端</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-23 21:39
 */
@Data
@Slf4j
@Service
public class NettyServer {

    @Autowired
    private ServerConnectionListener serverConnectionListener;
    @Autowired
    private ServerChannelCloseListener serverChannelCloseListener;
    @Autowired
    private ServerChannelInitializer serverChannelInitializer;

    @Value("${im.port:6500}")
    private int port;

    private EventLoopGroup boss;
    private EventLoopGroup work;
    private ServerBootstrap bootstrap;

    public void createServer() {
        this.boss = new NioEventLoopGroup(2);
        this.work = new NioEventLoopGroup(8);
        this.bootstrap = new ServerBootstrap();
        this.bootstrap.group(this.boss, this.work)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(serverChannelInitializer);
        try {
            this.bootstrap.bind(port)
                    .sync()
                    // 添加连接监听器
                    .addListener(serverConnectionListener)
                    .channel()
                    .closeFuture()
                    // 添加连接关闭监听器
                    .addListener(serverChannelCloseListener);
        } catch (InterruptedException e) {
            LogUtil.error(log, e);
        }
    }

    public void destroy() {
        boss.shutdownGracefully();
        work.shutdownGracefully();
    }
}
